/**
 * @param {*} arr 
 * 将数组转化成树结构
 */
export const recursive = (arr) => {
  if (Array.from(arr).length === 0 || !arr) return arr

  let arrMap = {}
  arr.forEach(item => {
    arrMap[item.id] = item
  })

  let arrTree = []
  arr.forEach(item => {
    let parent = arrMap[item.pid]
    if (parent) {
      (parent.children || (parent.children = [])).push(item);
    } else {
      arrTree.push(item)
    }
  })

  let arrFlat = arrTree.map((item, index) => {

    if (!item.children) return item

    let teamArr = [...item.children]
    let children = []
    while (teamArr.length !== 0) {
      let item = teamArr.pop()
      if (!item.children) {
        children.push(item)
      } else {
        teamArr.unshift(...item.children)
        Reflect.deleteProperty(item, 'children')
        children.push(item)
      }
    }
    // console.log(children, "CHILDREN")
    return Object.assign(item, {
      children: children
    })

  })
  // console.log(arrFlat, "Flat")
  // console.log(arrTree, "ArrTree")
  return arrFlat
}
